package netw;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Receiver extends Thread {
	
	DatagramSocket serverSocket;
	
	public Message playerCoords = new Message (0f, 0f, 0f, 0f, 0f, 0f);
	
	public Receiver() {
		try {
			serverSocket = new DatagramSocket(9876);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		try {
			System.out.println("Receiver up and running...");
			
	        byte[] receiveData = new byte[1024];// 1024????????
	        
			while(true) {
				DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
				serverSocket.receive(receivePacket);
				byte[] data = receivePacket.getData();
				
				ObjectInputStream iStream = new ObjectInputStream(new ByteArrayInputStream(data));
				Message m = (Message) iStream.readObject();
				iStream.close();

				System.out.println("received: " + m);
				
				if(m.z == -777) {
					break;
				}
				playerCoords = m;
				m = null;
			}
			serverSocket.close();
			
			System.out.println("Receiver shut down.");
		} catch (IOException | ClassNotFoundException e) {
			serverSocket.close();
			e.printStackTrace();
		}
	}
}